package com.morganfinance.submit;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

import com.example.maxfinance.GlobalData;
import com.example.maxfinance.HomeActivity;
import com.example.maxfinance.R;

public class CreditHistory {

	Activity parent;
	public View view;
	
	public static final int ERROR_NONE = -1;
	public static final int ERROR_GENERAL = 0;
	public static final int ERROR_TOTAL_OUTSTANDING = 1;
	
	public static final int CREDIT_HISTORY_TYPE_NONE =  0;
	public static final int CREDIT_HISTORY_TYPE_TOTAL_OUTSTANDING =  1;
	public static final int CREDIT_HISTORY_TYPE_DISCHARGED_DATE =  2;
	
	int 		nTypeCreditHistory;
	
	EditText edtNamePartner;
	EditText edtContactNumber;

	Button btnNoApplyBankruptcy;
	Button btnYesApplyBankruptcy;
	
	Spinner spnCreditHistory;

	Button	btnNoTakenOutLoan;
	Button	btnYesTakenOutLoan;
	Button	btnInfTakenOutLoan;
	
	CheckBox	chkAgreeCredit;
	
	String strHardShip = "";
	String strExistingClient = "";
	
	LinearLayout	llytTotalOutStandingValue;
	public EditText		edtTotalOutStandingValue;
	
	LinearLayout	llytDischarge;
	Spinner			spnDischargedDate;
	Button			btnNoDefaultAfterDischarge;
	Button			btnYesDefaultAfterDischarge;
	
	String			strDefaultAfterDischarge = "";
	
	public CreditHistory(Context context) {
		// TODO Auto-generated constructor stub
		parent = (Activity) context;
		initWidget();
		initValue();
		initEvent();
	}
	
	private void initWidget() {
    	LayoutInflater inflater = parent.getLayoutInflater();
    	view = inflater.inflate(R.layout.credit_history_layout, null);
    	
    	edtNamePartner = (EditText) view.findViewById(R.id.partner_name_editText);
    	edtContactNumber = (EditText) view.findViewById(R.id.current_value_editText1);
    	
    	btnNoApplyBankruptcy = (Button) view.findViewById(R.id.no_person_with_good_history_button);
    	btnYesApplyBankruptcy = (Button) view.findViewById(R.id.yes_person_with_good_history_button);
    	
    	spnCreditHistory = (Spinner) view.findViewById(R.id.registered_owner_name_spinner1);
    	
    	btnNoTakenOutLoan = (Button) view.findViewById(R.id.inf_brand_button1);
    	btnYesTakenOutLoan = (Button) view.findViewById(R.id.inf_model_button1);
    	btnInfTakenOutLoan = (Button) view.findViewById(R.id.inf_under_finance_button1);
    	
    	chkAgreeCredit = (CheckBox) view.findViewById(R.id.agree_credit_checkbox);

    	llytTotalOutStandingValue = (LinearLayout) view.findViewById(R.id.total_outstanding_value_layout);
    	edtTotalOutStandingValue = (EditText) view.findViewById(R.id.total_outstanding_value_editText);
    	
    	
    	llytDischarge = (LinearLayout) view.findViewById(R.id.discharge_layout);
    	spnDischargedDate = (Spinner) view.findViewById(R.id.discharged_date_spinner);
    	
    	btnNoDefaultAfterDischarge = (Button) view.findViewById(R.id.no_default_after_discharge_button);
    	btnYesDefaultAfterDischarge = (Button) view.findViewById(R.id.yes_default_after_discharge_button);
    	
    	llytTotalOutStandingValue.setVisibility(View.GONE);
    	llytDischarge.setVisibility(View.GONE);
    	nTypeCreditHistory = CREDIT_HISTORY_TYPE_NONE;
	}
	
	private void initEvent() {
		btnNoApplyBankruptcy.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
//				showGeneralAlert("", "Email is crucial for communication during the application process");
				strHardShip = "No";
				btnNoApplyBankruptcy.setBackgroundResource(R.drawable.no_sel);
				btnYesApplyBankruptcy.setBackgroundResource(R.drawable.yes_normal);
			}
        });
		btnYesApplyBankruptcy.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
//				showGeneralAlert("", "Email is crucial for communication during the application process");
				new AlertDialog.Builder(parent)
		        .setTitle("Hardship")
		        .setMessage("Have you ever applied for:\n" +
		        		"FINANCIAL HARDSHIP - formal arrangement with a credit provider to ease repayments on " +
		        		"grounds of financial hardship. (not include adjustment on repayment frequency / date)\n\n" +
		        		"OR\n\n" + 
		        		"BANKRUPTCY/PART9 DEBT AGREEMENT\n" +
		        		"-this includes debt agreement setup to consolidate your all your debts."
		        )
		        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) { 
		                // continue with delete
		            	strHardShip = "Yes";
						btnNoApplyBankruptcy.setBackgroundResource(R.drawable.no_normal);
						btnYesApplyBankruptcy.setBackgroundResource(R.drawable.yes_sel);
		            }
		         })
		         .setNegativeButton("No", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) { 
		                // continue with delete
		            	strHardShip = "No";
						btnNoApplyBankruptcy.setBackgroundResource(R.drawable.no_sel);
						btnYesApplyBankruptcy.setBackgroundResource(R.drawable.yes_normal);
		            }
		         })
		         .show();
			}
        });
		
		btnNoTakenOutLoan.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
//				showGeneralAlert("", "Email is crucial for communication during the application process");
				strExistingClient = "No";
				btnNoTakenOutLoan.setBackgroundResource(R.drawable.no_sel);
				btnYesTakenOutLoan.setBackgroundResource(R.drawable.yes_normal_middle);
			}
        });
		
		btnYesTakenOutLoan.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
//				showGeneralAlert("", "Email is crucial for communication during the application process");
				strExistingClient = "Yes";
				btnNoTakenOutLoan.setBackgroundResource(R.drawable.no_normal);
				btnYesTakenOutLoan.setBackgroundResource(R.drawable.yes_sel_middle);
			}
        });
		btnInfTakenOutLoan.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showGeneralAlert("Information", "If a loan has not be taken out before, click No.");
			}
        });
		
		btnNoDefaultAfterDischarge.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				strDefaultAfterDischarge = "No";
				btnNoDefaultAfterDischarge.setBackgroundResource(R.drawable.no_sel);
				btnYesDefaultAfterDischarge.setBackgroundResource(R.drawable.yes_normal);
			}
        });
		
		btnYesDefaultAfterDischarge.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				strDefaultAfterDischarge = "Yes";
				btnNoDefaultAfterDischarge.setBackgroundResource(R.drawable.no_normal);
				btnYesDefaultAfterDischarge.setBackgroundResource(R.drawable.yes_sel);
			}
        });
		
		spnCreditHistory.setOnItemSelectedListener(new OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
		        // your code here
		    	if (position <= 1 || position == 5 || position == 7) {
		        	llytTotalOutStandingValue.setVisibility(View.GONE);
		        	llytDischarge.setVisibility(View.GONE);
		        	nTypeCreditHistory = CREDIT_HISTORY_TYPE_NONE;
		    	}
		    	if (position > 1 && position < 5) {
		        	llytTotalOutStandingValue.setVisibility(View.VISIBLE);
		        	llytDischarge.setVisibility(View.GONE);
		        	nTypeCreditHistory = CREDIT_HISTORY_TYPE_TOTAL_OUTSTANDING;
		    	}
		    	if (position == 6 || position == 9) {
		        	llytTotalOutStandingValue.setVisibility(View.GONE);
		        	llytDischarge.setVisibility(View.VISIBLE);
		        	nTypeCreditHistory = CREDIT_HISTORY_TYPE_DISCHARGED_DATE;
		    	}
		    }

		    @Override
		    public void onNothingSelected(AdapterView<?> parentView) {
		        // your code here
		    }

		});
	}
	
	private void initValue() {
		ArrayAdapter<String> spinnerArrayAdapter;
		
		spinnerArrayAdapter = new ArrayAdapter<String>(parent, android.R.layout.simple_spinner_item, GlobalData.itemsOfCreditHistory);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnCreditHistory.setAdapter(spinnerArrayAdapter);
		
		spinnerArrayAdapter = new ArrayAdapter<String>(parent, android.R.layout.simple_spinner_item, GlobalData.itemsOfDischargedDate);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnDischargedDate.setAdapter(spinnerArrayAdapter);
		
		loadSavedPreferences();
	}
	
	public void loadSavedPreferences() {
    	
    	SharedPreferences sharedPreferences = HomeActivity.sharedPreferences;
    	
    	 String str;
         int n;
    	    	
         str = sharedPreferences.getString("strNamePartner", "");
         edtNamePartner.setText(str);
         str = sharedPreferences.getString("strContactNumber", "");
         edtContactNumber.setText(str);
         str = sharedPreferences.getString("strHardShip1", "");
      	 strHardShip = str;

         if (str == "Yes") {
				btnNoApplyBankruptcy.setBackgroundResource(R.drawable.no_normal);
				btnYesApplyBankruptcy.setBackgroundResource(R.drawable.yes_sel);
         }
         if (str == "No") {
				btnNoApplyBankruptcy.setBackgroundResource(R.drawable.no_sel);
				btnYesApplyBankruptcy.setBackgroundResource(R.drawable.yes_normal);
         }
         n = sharedPreferences.getInt("nCreditHistory", 0);
         spnCreditHistory.setSelection(n);
         str = sharedPreferences.getString("strTotalOutstanding", "");
         edtTotalOutStandingValue.setText(str);
         n = sharedPreferences.getInt("nDischargedDate", 0);
         spnDischargedDate.setSelection(n);
         str = sharedPreferences.getString("strDefaultAfterDischage", "");
         strDefaultAfterDischarge = str;
         if (str == "Yes") {
				btnNoDefaultAfterDischarge.setBackgroundResource(R.drawable.no_normal);
				btnYesDefaultAfterDischarge.setBackgroundResource(R.drawable.yes_sel);
         }
         if (str == "No") {
				btnNoDefaultAfterDischarge.setBackgroundResource(R.drawable.no_sel);
				btnYesDefaultAfterDischarge.setBackgroundResource(R.drawable.yes_normal);
         }
         str = sharedPreferences.getString("strExistingClient", "");
         strExistingClient = str;
         if (str == "Yes") {
			btnNoTakenOutLoan.setBackgroundResource(R.drawable.no_normal);
			btnYesTakenOutLoan.setBackgroundResource(R.drawable.yes_sel_middle);
         }
         if (str == "No") {
			btnNoTakenOutLoan.setBackgroundResource(R.drawable.no_sel);
			btnYesTakenOutLoan.setBackgroundResource(R.drawable.yes_normal_middle);
         }
    }
    
    public void savePreferences() {
    	SharedPreferences sharedPreferences = HomeActivity.sharedPreferences;
    	SharedPreferences.Editor editor = sharedPreferences.edit();
    	
   	 	editor.putString("strNamePartner", edtNamePartner.getText().toString());
   	 	editor.putString("strContactNumber", edtContactNumber.getText().toString());
   	 	editor.putString("strHardShip1", strHardShip);
   	 	editor.putInt("nCreditHistory", spnCreditHistory.getSelectedItemPosition());
   	 	editor.putString("strTotalOutstanding", edtTotalOutStandingValue.getText().toString());
   	 	editor.putInt("nDischargedDate", spnDischargedDate.getSelectedItemPosition());
   	 	editor.putString("strDefaultAfterDischage", strDefaultAfterDischarge);
   	 	editor.putString("strExistingClient", strExistingClient);

   	 	editor.commit();
    }
	
	public void showGeneralAlert(String title, String message) {
    	new AlertDialog.Builder(parent)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // continue with delete
            }
         })
         .show();
    }
	
	public int checkInput() {
		
		String str;
		if (strHardShip.equals("")) {
    		showGeneralAlert("Question", "Did you ever applied for bankruptcy or hardship?");
    		return ERROR_GENERAL;
		}
    	str = GlobalData.itemsOfTitle[(int) spnCreditHistory.getSelectedItemId()];
    	if (str == "-Select-") {
    		showGeneralAlert("Select", "Please select Your Credit History!");
    		return ERROR_GENERAL;
    	}
    	
    	if (nTypeCreditHistory == CREDIT_HISTORY_TYPE_TOTAL_OUTSTANDING) {
    		str = edtTotalOutStandingValue.getText().toString();
    		if (str.equals("")) {
        		showGeneralAlert("Input", "Please input Total outstanding value!");
        		return ERROR_TOTAL_OUTSTANDING;
    		}
    	}
    	
    	if (nTypeCreditHistory == CREDIT_HISTORY_TYPE_DISCHARGED_DATE) {
    		str = GlobalData.itemsOfDischargedDate[(int) spnDischargedDate.getSelectedItemId()];
    		if (str == "-Select-") {
        		showGeneralAlert("Select", "Please select a Discharged date!");
        		return ERROR_GENERAL;
    		}    	
    	}
    	if (nTypeCreditHistory == CREDIT_HISTORY_TYPE_DISCHARGED_DATE) {
    		if (strDefaultAfterDischarge.equals("")) {
    			showGeneralAlert("Question", "Did you have any default after discharge?");
    			return ERROR_GENERAL;
    		}
    	}
    	
    	if (strExistingClient.equals("")) {
			showGeneralAlert("Question", "Have your taken out a loan with us before?");
			return ERROR_GENERAL;
    	}
    	if (!chkAgreeCredit.isChecked()) {
    		showGeneralAlert("Check", "Please Check to agree!");
    		return ERROR_GENERAL;
    	}
    	
//    	public String strTotalOutstanding = "";
//    	public String strDischargedDate = "";
//    	public String strDefaultAfterDischage = "";
    	
    	GlobalData.personalInfo.strNamePartner = edtNamePartner.getText().toString();
    	GlobalData.personalInfo.strContactNumber = edtContactNumber.getText().toString();
    	GlobalData.personalInfo.strHardShip1 = strHardShip;
    	GlobalData.personalInfo.strCreditHistory = GlobalData.itemsOfCreditHistory[(int) spnCreditHistory.getSelectedItemId()];
    	if (nTypeCreditHistory == CREDIT_HISTORY_TYPE_TOTAL_OUTSTANDING) {
    		GlobalData.personalInfo.strTotalOutstanding = edtTotalOutStandingValue.getText().toString();
    	}
    	if (nTypeCreditHistory == CREDIT_HISTORY_TYPE_DISCHARGED_DATE) {
    		GlobalData.personalInfo.strDischargedDate = 
    				GlobalData.itemsOfDischargedDate[(int) spnDischargedDate.getSelectedItemId()];
    	}
    	
    	GlobalData.personalInfo.strExistingClient = strExistingClient;

    	return ERROR_NONE;
	}
}
